package main

import (
	"log"
	"time"

	"github.com/gomodule/redigo/redis"
)

//使用封装方法的办法 简化数据库
func main() {
	//方法都被封装了 这里只需要调用即可
	reply, err := dbExec("name", "丁杨维")
	if err != nil {
		log.Println(err)
	}
	log.Println(reply)
	reply2, err2 := dbQuery("name")
	if err2 != nil {
		log.Println(err2)
	}
	log.Println(reply2)
}

func dbExec(key string, value string) (reply string, err error) {
	pool := newPool()
	conn := pool.Get()
	defer conn.Close()
	reply = "fail!"
	_, err = conn.Do("set", key, value)
	if err != nil {
		return
	}
	reply = "succeed!"
	return
}
func newPoolFunc() (redis.Conn, error) {
	var (
		timeout      time.Duration
		readTimeOut  time.Duration
		writeTimeOut time.Duration
	)
	timeout = 5 * time.Second
	readTimeOut = 5 * time.Second
	writeTimeOut = 5 * time.Second

	return redis.Dial("tcp", "81.68.186.20:6379",
		redis.DialDatabase(0),
		redis.DialPassword("ffdd2021@"),
		redis.DialConnectTimeout(timeout),
		redis.DialReadTimeout(readTimeOut),
		redis.DialWriteTimeout(writeTimeOut))
}

func dbQuery(key string) (reply string, err error) {
	p := newPool()
	defer p.Close()
	c := p.Get()
	defer c.Close()
	reply, err = redis.String(c.Do("get", key))
	if err != nil {
		return
	}
	return
}
func newPool() *redis.Pool {
	return &redis.Pool{
		MaxIdle: 10,
		Dial:    newPoolFunc,
		Wait:    true,
	}
}
